package com.upcode.weighing.service.impl;

import com.upcode.weighing.domain.SysRes;
import com.upcode.weighing.service.MenuTreeService;
import com.upcode.weighing.vo.resp.pc.MenuTreeVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class MenuTreeAndButtonSreviceImpl implements MenuTreeService {
    @Override
    public void menuTreeGroup(MenuTreeVo pItem, List<? extends SysRes> items) {

        List<MenuTreeVo> menusAndButtons = items.stream()
                .filter(item ->item.getPid().equals(pItem.getId()))
                .map(item -> new MenuTreeVo(item.getId(), item.getPid(), item.getName(),item.getPermission(), item.getUrl(),item.getSortNum(), item.getIcon1(),item.getIcon2(), item.getType(),item.getDes()))
                .collect(Collectors.toList());

        List<MenuTreeVo> menus = menusAndButtons.stream()
                .filter(item -> item.getType() == 1)
                .sorted(Comparator.comparingInt(item -> Optional.ofNullable(item.getSortNum()).orElse(0)))
                .collect(Collectors.toList());

        List<MenuTreeVo> buttons = menusAndButtons.stream()
                .filter(item -> item.getType() == 2)
                .collect(Collectors.toList());
        pItem.setButtonList(buttons);
        if(menus == null || menus.isEmpty()) {
            return;
        }
        pItem.setChildrenMenuTree(menus);
        for(MenuTreeVo item : menus) {
            menuTreeGroup(item,items);
        }
    }

    @Override
    public void menuTree(MenuTreeVo pItem, List<? extends SysRes> items) {
        List<MenuTreeVo> menusAndButtons = items.stream()
                .filter(item ->item.getPid().equals(pItem.getId()))
                .map(item -> new MenuTreeVo(item.getId(), item.getPid(), item.getName(),item.getPermission(), item.getUrl(),item.getSortNum(), item.getIcon1(),item.getIcon2(), item.getType(),item.getDes()))
                .collect(Collectors.toList());

        List<MenuTreeVo> menus = menusAndButtons.stream()
                .filter(item -> item.getType() == 1)
                .sorted(Comparator.comparingInt(item -> Optional.ofNullable(item.getSortNum()).orElse(0)))
                .collect(Collectors.toList());
        if(menus == null || menus.isEmpty()) {
            return;
        }
        pItem.setChildrenMenuTree(menus);
        for(MenuTreeVo item : menus) {
            menuTree(item,items);
        }
    }
}

